<?php
declare (strict_types = 1);
namespace app\adminapi\logic;
use adminmatrix\server\app\logic\BaseLogic;
use adminmatrix\annotation\Inject;
use app\adminapi\model\system\auth\AdminUser;
use app\adminapi\service\AdminTokenService;
use think\exception\HttpException;
use think\exception\ValidateException;

class LoginLogic extends BaseLogic
{
    #[Inject]
    # 你的模型
    protected AdminUser $model;

    public static function login($request ) : array
    {
        $time = time();
        try {
            $params = $request->post();
            validate([
                'username'      =>  'require',
                'password'      =>  'require',
            ])->message([
                'username.require'  =>  '管理员账号不能为空',
                'password.require'  =>  '管理员密码不能为空',
            ]) -> check($params);
            $user = (new AdminUser) -> where('username' , $params['username']) -> findOrEmpty();
//            halt(md5($params['password'] .$user->salt));
            if ($user->isEmpty()) throw new HttpException(200 , '管理员账号或密码错误');
            if ($user->password !== md5($params['password'] . $user->salt))
                throw new HttpException(200 , '管理员账号或密码错误');

            $user->last_login_time = $time;
            $user->last_login_ip   = $request->ip();
            $user->save();

            // 设置token
            $adminInfo = AdminTokenService::setToken($user->id , $params['terminal'] , $user->multipoint_login);
            return $adminInfo;
        } catch (HttpException | ValidateException $e )
        {
            throw new HttpException($e->getCode() , $e->getMessage());
        }

    }

    public function logout($adminInfo)
    {

        //token不存在，不注销
        if (!isset($adminInfo['token'])) {
            return false;
        }
        //设置token过期
        return AdminTokenService::expireToken($adminInfo['token']);

    }
}